import json
import re

from django.shortcuts import render
from meiduo_mall.utils.views import LoginRequiredJsonMixin
# Create your views here.
from django.http import JsonResponse
from django.views import View
import logging

from apps.users.models import Address

logger = logging.getLogger('meiduo')

class CreateAddressView(LoginRequiredJsonMixin,View):
    """新增地址"""

    def post(self, request):
        # 获取当前地址个数
        try:
            count = request.user.addresses.filter(is_deleted=False).count()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code':400,
                'errmsg':'获取地址数据失败'
            })

        if count >= 20:
            return JsonResponse({
                'code':400,
                'errmsg':'超过数量限制，添加失败'
            })
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})
        # 往数据库新增地址
        try:
            address = Address.objects.create(
                user=request.user,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                title = receiver,
                receiver = receiver,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email)
            # 是否设置了默认地址
            if not request.user.default_address:
                request.user.default_address=address
                request.user.save()
        except Exception as e :
            logger.error(e)
            return JsonResponse({
                'code':400,
                'errmsg':'添加失败'
            })
        # 构建地址信息字典
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district":address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': 0,
                                  'errmsg': '新增地址成功',
                                  'address':address_dict})


class AddressesView(LoginRequiredJsonMixin,View):
    def get(self,request):
        """
        展示收货地址
        :param request:
        :return:
        """
        user = request.user
        # 没被删除的地址查询集
        address_model_list = user.addresses.filter(is_deleted=False)
        address_list = []
        for address_model in address_model_list:
            # 构建地址字典
            address_dict={
                    "id": address_model.id,
                    "title": address_model.title,
                    "receiver": address_model.receiver,
                    "province": address_model.province.name,
                    "city": address_model.city.name,
                    "district": address_model.district.name,
                    "place": address_model.place,
                    "mobile": address_model.mobile,
                    "tel": address_model.tel,
                    "email": address_model.email
                }
            # 默认地址放在列表首位
            if user.default_address_id == address_model.id:
                address_list.insert(0,address_dict)
            else:
                address_list.append(address_dict)


        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            "default_address_id": user.default_address_id,
            "addresses": address_list
        })


class UpdateDestroyAddressView(View):
    def put(self,request,address_id):
        """
        修改地址
        :param request:
        :return:
        """
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile,address_id]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})
        try:
            # 查询集支持update
            address = Address.objects.filter(id=address_id)
        except Exception as e :
            return JsonResponse({
                'code':400,'errmsg':'地址不存在，无法修改'
            })
        try:
            address.update(
                receiver=receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place =place,
                mobile =mobile,
                tel =tel,
                email =email)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,'errmsg':'更新地址失败'})
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})

    def delete(self,request,address_id):
        """
        删除地址
        :param request:
        :return:
        """
        try:
            address= Address.objects.filter(id=address_id)
            address.update(
                is_deleted=True
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,'errmsg':'删除地址失败'})
        return JsonResponse({'code':0,'errmsg':'删除成功'})


class AddressDefaultView(View):
    def put(self,request,address_id):
        """
        设置默认地址  也就是修改默认地址字段值
        :param request:
        :return:
        """
        try:
            request.user.default_address_id=address_id
            request.user.save()
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'设置默认地址失败'})
        return JsonResponse({'code':0,'errmsg':'设置成功'})


class UpdateTitleAddressView(View):
    def put(self,request,address_id):
        """
        修改地址标题
        :param reuqest:
        :param address_id:
        :return:
        """
        data = json.loads(request.body.decode())
        title = data.get('title')
        try:
            addresses = Address.objects.filter(id=address_id)
            addresses.update(
                title=title
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,'errmsg':'修改失败'})
        return JsonResponse({'code':0,'errmsg':'修改成功'})